import {
  baseUrl,
  prefixUrl
} from '../../config/api'
let app = getApp()
import Message from 'tdesign-miniprogram/message/index';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 工单列表
    typeOption: {},
    typeList: app.globalData.typeList,
    activeValues: [],
    memo: '',
    // 时间选择
    mode: '',
    datetimeVisible: false,
    endDateTimeVisible: false,
    datetime: new Date().getTime(),
    endDateTime: new Date().getTime(),
    datetimeText: '',
    endDateTimeText: '',
    repairEntity: {
      "userType": "",
      "userName": "",
      "userId": "",
      "department": "",
      "faultLocation": "",
      "describe": "",
      "contactWay": "",
      "userNo": "",
    },
    // 文件上传
    fileList: [],
    filePath: '',
    //文本输入框样式
    textareaStyle: 'height: 280rpx',
    showDialog: false,
    confirmBtn: {
      content: '知道了',
      variant: 'base'
    },
    viewer: {
      visible: false,
      showIndex: false,
      closeBtn: false,
      images: [],
    },
  },
  DownLoad() {

  },
  viewerOnClose() {
    this.setData({
      viewer: {
        visible: false,
      },
    })
  },
  onShow() {
    this.init()
  },
  closeDialog() {
    this.setData({
      showDialog: false
    })
  },
  openDialog() {
    this.setData({
      showDialog: true
    })
  },
  handleChange(e) {
    this.setData({
      activeValues: e.detail.value,
    });
  },
  init() {},
  // 工单类型的回调
  showCascader() {
    this.setData({
      visible: true
    });
  },
  preview(e) {
    console.log(e)
    this.setData({
      viewer: {
        images: [
          e.currentTarget.dataset.item
        ],
        showIndex: true,
        visible: true,
        closeBtn: true
      }
    });
  },
  // 选中的回调
  // onPick(e) {
  //   console.log('onPick',e.detail);
  // },
  // 改变的回调
  onChange(e) {
    console.log("e", e.detail);
    const {
      selectedOptions,
      value 
    } = e.detail;

    let foundParent = null;
    let foundChild = null;

    // 使用 .some() 替代 .find()，当找到后可以提前终止循环
    this.data.typeList.some(parent => {
      if (parent.children) {
        // 在子节点中查找
        const childMatch = parent.children.find(child => child.value === value);
        
        if (childMatch) {
          // 找到了！
          foundParent = parent;       // 存储找到的父对象
          foundChild = childMatch;    // 存储找到的子对象（这个是完整的）
          return true; // 终止 .some() 循环
        }
      }
      return false; // 继续查找下一个父节点
    });

    // 2. 检查是否找到，并 setData
    if (foundChild && foundParent) {
      // 找到了，使用我们找到的 *完整* 对象
      this.setData({
        value, // 更新 t-cascader 的绑定值
        note: selectedOptions.map((item) => item.label).join('/'),
        
        typeOption: foundChild,
        typeTop: foundParent.value 
      });

      console.log("成功找到并设置 typeOption (包含 templateId):", foundChild);

    } else {
      // 兜底：万一没找到（例如数据异常）
      console.warn("未能从 typeList 中匹配到 value:", value);
      this.setData({
        value,
        note: selectedOptions.map((item) => item.label).join('/'),
        typeOption: {},
        typeTop: null
      });
    }
  },

  // 时间选择的一些回调
  showPicker(e) {
    const {
      mode
    } = e?.currentTarget?.dataset;
    this.endDateTime = this.datetime
    this.setData({
      mode,
      [`${mode}Visible`]: true,
    });
  },
  hidePicker() {
    const {
      mode
    } = this.data;

    this.setData({
      [`${mode}Visible`]: false,
    });
  },
  onConfirm(e) {
    const {
      value
    } = e?.detail;
    const {
      mode
    } = this.data;

    this.setData({
      [mode]: value,
      [`${mode}Text`]: value,
    });

    this.hidePicker();
  },

  onColumnChange(e) {
    // console.log('pick', e?.detail?.value);
  },
  addApproach() {
    // 审批类工单必须上传附件
    if(this.data.fileList.length <= 0 && this.data.typeOption.pid === 1){
      wx.showToast({
        title: "请先上传文件",
        icon: 'error',
        duration: 1000
      });
      return;
    }

    if (this.data.typeOption === undefined || this.data.typeOption.value === undefined) {
      return;
    }
    wx.getStorageInfoSync()
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    let userInfo = JSON.parse(wx.getStorageSync("userInfo"))
    let _this = this
    wx.request({
      url: baseUrl + 'sys/worksheetRecord/save',
      method: 'post',
      data: {
        'applicantId': userInfo.userId,
        'worksheetType': _this.data.typeOption.value,
        'memo': _this.data.memo,
        "filePath": _this.data.filePath,
        'worksheetTypePid' : _this.data.typeOption.pid,
        "repairEntity": {
          "userType": userInfo.type,
          "userName":  _this.data.userName,
          "userId":  userInfo.userId,
          "department":  _this.data.department,
          "faultLocation":  _this.data.faultLocation,
          "problemDesc":  _this.data.describe,
          "contactWay":  _this.data.contactWay,
          "userNo":  _this.data.userNo,
        }
      },
      success(res) {
        wx.hideLoading()
        if (res.data.code === 0) {
          wx.showToast({
            title: '申请成功',
            icon: 'success',
            duration: 1000,
            success() {
              setTimeout(function () {
                wx.navigateBack()
              }, 1000)
            }
          });
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'error',
            duration: 2000
          });
        }
      }
    })
  },
  //文件上传的回调
  handleAdd(e) {
    this.onUpload(e.detail.files[0])
  },
  onUpload(file) {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    let _this = this
    wx.uploadFile({
      url: baseUrl + 'sys/file/addFile',
      filePath: file.url,
      name: 'file',
      success: (res) => {
        let resq = JSON.parse(res.data)
        wx.hideLoading()
        if (resq.code === 0) {
          console.log(prefixUrl)
          _this.setData({
            fileList: [...this.data.fileList, {
              url: prefixUrl + resq.url,
              type: 'image',
              status: 'done'
            }],
            filePath: resq.url
          });
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'error',
            duration: 2000
          })
        }
      },
      fail(res) {
        wx.hideLoading()
        console.log(res)
      }
    });

  },
  //文件移除的回调
  handleRemove(e) {
    const {
      index
    } = e.detail;
    const {
      fileList
    } = this.data;

    fileList.splice(index, 1);
    this.setData({
      fileList,
    });
  },
})